package com.tensai.core.mvc.base.service.imp;

import com.tensai.core.mvc.base.dao.IUuidDao;
import com.tensai.core.mvc.base.entry.UuidEntity;
import com.tensai.core.mvc.base.service.IUuidService;
import com.tensai.core.mvc.base.tools.ResultJson;
import com.tensai.core.constant.ResponseStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 以UUID为主键的实体类Service的基本实现类，以UUID为主键的实体类Service必须继承此类
 * @author Tensai
 *         2018-03-09 15:46
 */
@Service
public abstract class BaseUuidServiceImpl<T extends UuidEntity, K extends IUuidDao<T>> extends BaseServiceImpl<T, String, K> implements IUuidService<T, K> {

	/**
	 * 批量删除数据
	 * @param qids  id集合（以逗号分隔）
	 * @return  删除结果
	 */
	@Override
	@Transactional(rollbackFor=Exception.class)
	public ResultJson deletes(String qids) {
		ResultJson resultJson;
		String[] ids = qids.split(",");
		List<String> uuidList = Arrays.asList(ids);
		getDao().deleteByUuidIn(uuidList);
		resultJson = new ResultJson(ResponseStatus.DELETES_SUCCESS);
		return resultJson;
	}

	/**
	 * 保存当前实体
	 * @param t     实体对象
	 * @return      保存结果
	 */
	@Override
	public ResultJson save(T t) {
		if (t != null) {
			if (StringUtils.isEmpty(t.getUuid())) {
				t.setUuid(UUID.randomUUID().toString());
			}
			getDao().save(t);
			return new ResultJson(ResponseStatus.SAVE_SUCCESS);
		}
		ResultJson resultJson;
		resultJson = new ResultJson(ResponseStatus.SAVE_FAILURE);
		resultJson.addData("error", "请检查保存的数据是否为空");
		return resultJson;
	}
}
